package com.shiguiwu.springmybatis.websocket;

/**
 * @description:
 * @author: stone
 * @date: Created by 2022/3/14 19:49
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.websocket
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/socket")
public class WebSocketController {

    @Autowired
    private HttpServletRequest request1;


    //推送数据接口
    @ResponseBody
    @GetMapping("/socket/push/{cid}")
    public Map<String, Object> pushToWeb(@PathVariable String cid, String message,HttpServletRequest request) {
        String id = getPathParam(request1, "id");
        String cid1 = getPathParam(request1, "cid");
        Map<String, Object> result = new HashMap<>();
        try {
            //WebSocketServer.sendInfo(message, cid);
            result.put("code", cid);
            result.put("msg", message);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public  String getPathParam(HttpServletRequest request, String variableName) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        String s = pathMatcher.extractUriTemplateVariables(pattern, path).get(variableName);
        log.warn("Path info is null for request: {}", request.getRequestURI());

        return s;
    }


    public static String getPathVariable(HttpServletRequest request, String variableName) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return pathMatcher.extractUriTemplateVariables(pattern, path).get(variableName);
    }
}





